package com.lu.bio;

import java.io.*;
import java.net.Socket;

/**
 * @program lu-netty
 * @description: 应用场景-处理器
 * @author: zhanglu
 * @create: 2022-06-09 14:53:00
 */
public class ChannelHandler {

    private Socket socket;
    private String charset;
    private BufferedReader in;
    private PrintWriter out;

    public ChannelHandler(Socket socket, String charset) {
        this.socket = socket;
        this.charset = charset;
        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), this.charset));
            out = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                in.close();
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public BufferedReader in(){
        return in;
    }

    public PrintWriter out(){
        return out;
    }

    public void close(){
        try {
            out.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void writeAndFlush(Object msg){
        out.println(msg.toString());
    }

    public Socket socket(){
        return this.socket;
    }

}
